package com.droidclaimcustomer.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.droidclaimcustomer.GCMIntentService;
import com.droidclaimcustomer.R;
import com.droidclaimcustomer.bl.DroidClaimBlService;
import com.droidclaimcustomer.dto.AuthenCustomerBlDto;
import com.droidclaimcustomer.dto.AuthenCustomerResultBlDto;
import com.droidclaimcustomer.dto.CustomerBlDto;
import com.droidclaimcustomer.helper.asyntask.ICompleteListener;
import com.google.android.gcm.GCMRegistrar;
import com.googlecode.tesseract.android.TessBaseAPI;

public class LoginActivity extends Activity implements ICompleteListener {

	private final int CAMERA_REQUEST_INTENT = -1;
	public static final String PACKAGE_NAME = "com.droidclaimcustomer.activity";
	public static final String DATA_PATH = Environment
			.getExternalStorageDirectory().toString() + "/droidclaimcustomer/";

	// You should have the trained data file in assets folder
	// You can get them at:
	// http://code.google.com/p/tesseract-ocr/downloads/list
	public static final String lang = "eng";
	protected static final String PHOTO_TAKEN = "photo_taken";
	private static final String TAG = "LoginActivity.java";
	protected String _path;
	protected boolean _taken;
	
	
	private EditText licensePlateET;
	private EditText passwordET;
	private String loginTaskId;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		

		String[] paths = new String[] { DATA_PATH, DATA_PATH + "tessdata/" };

		for (String path : paths) {
			File dir = new File(path);
			if (!dir.exists()) {
				if (!dir.mkdirs()) {
					Log.v(TAG, "ERROR: Creation of directory " + path
							+ " on sdcard failed");
					return;
				} else {
					Log.v(TAG, "Created directory " + path + " on sdcard");
				}
			}

		}
		if (!(new File(DATA_PATH + "tessdata/" + lang + ".traineddata"))
				.exists()) {
			try {

				AssetManager assetManager = getAssets();
				InputStream in = assetManager.open("tessdata/"+lang+".traineddata");
				// GZIPInputStream gin = new GZIPInputStream(in);
				OutputStream out = new FileOutputStream(DATA_PATH
						+ "tessdata/"+lang+".traineddata");

				// Transfer bytes from in to out
				byte[] buf = new byte[1024];
				int len;
				// while ((lenf = gin.read(buff)) > 0) {
				while ((len = in.read(buf)) > 0) {
					out.write(buf, 0, len);
				}
				in.close();
				// gin.close();
				out.close();

				Log.v(TAG, "Copied " + lang + " traineddata");
			} catch (IOException e) {
				Log.e(TAG,
						"Was unable to copy " + lang + " traineddata "
								+ e.toString());
			}
		}

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		
		licensePlateET = (EditText) findViewById(R.id.licenseplate_ET);
	    passwordET = (EditText) findViewById(R.id.password_ET);
	    
		_path = DATA_PATH + "/ocr.jpg";
		
//		Intent intent = new Intent(LoginActivity.this, MainActivity.class);
//			
//		intent.putExtra("licensePlate", "");
//		intent.putExtra("name", "");
//		intent.putExtra("surname", "");
//		intent.putExtra("mobile", "");
//		intent.putExtra("custImg", "");
//		intent.putExtra("carModel", "");
//		intent.putExtra("carImg", "");
//		intent.putExtra("carColor", "");
//		intent.putExtra("carBrand", "");
//		intent.putExtra("insurancePackage", "");
//		
//		startActivity(intent);
		RegisterWithGCM();
		
				
	}

	private void RegisterWithGCM() {
		GCMRegistrar.checkDevice(this);
		GCMRegistrar.checkManifest(this);
		GCMIntentService.registrationId = GCMRegistrar.getRegistrationId(this);
		if (GCMIntentService.registrationId.equals("")) {
			GCMRegistrar.register(this, "344698691373"); // Note: get the sender
															// id from
															// configuration.
		} else {

			Log.v("Registration", "Already registered, registrationId: " + GCMIntentService.registrationId);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}

	public void handleClick(View target) {
		if (target.getId() == R.id.btnLogin) {
			
		    String username = licensePlateET.getText().toString();
		    String user_Password = passwordET.getText().toString();
		    AuthenCustomerBlDto auth_dto = new AuthenCustomerBlDto();
		    auth_dto.setLicensePlate(username);
		    auth_dto.setPassword(user_Password);
		    auth_dto.setRegistrationId(GCMIntentService.registrationId);
			DroidClaimBlService bl = new DroidClaimBlService(this);
			loginTaskId = bl.AuthenCustomer(auth_dto);
			
			
			
		}
	}
	
	public void onClickOCR(View target) {
		if (target.getId() == R.id.ocr_image) {

			Log.v(TAG, "Starting Camera app");
			startCameraActivity();
			
			
		}
	}
	
	protected void startCameraActivity() {
		File file = new File(_path);
		Uri outputFileUri = Uri.fromFile(file);

		final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

		startActivityForResult(intent, 0);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		Log.i(TAG, "resultCode: " + resultCode);

		if (resultCode == CAMERA_REQUEST_INTENT) {
			onPhotoTaken();
		} else {
			Log.v(TAG, "User cancelled");
		}
	}
	
	@Override
	public void onTaskCompleteSuccess(String taskId, Object result) {
		// TODO Auto-generated method stub
		if(taskId==loginTaskId){
			AuthenCustomerResultBlDto dto = (AuthenCustomerResultBlDto)result;
			if(dto.getSessionId() != null && !dto.getSessionId().isEmpty()){
				CustomerBlDto cust_dto = dto.getCustomerInfo();
				MainActivity.setSessionId(dto.getSessionId());
				MainActivity.setLicensePlate(cust_dto.getLicensePlate());
				MainActivity.setOwnerName(cust_dto.getName() + " " + cust_dto.getSurname());
				String carDetail = cust_dto.getCarBrand() + " " + cust_dto.getCarModel() + " " + cust_dto.getCarColor();
				MainActivity.setCarDetail(carDetail);
				
				Intent intent = new Intent(LoginActivity.this, MainActivity.class);
				//Bundle bundle = intent.getExtras();
					
				intent.putExtra("licensePlate", cust_dto.getLicensePlate());
				intent.putExtra("name", cust_dto.getName());
				intent.putExtra("surname", cust_dto.getSurname());
				intent.putExtra("mobile", cust_dto.getMobile());
				intent.putExtra("custImg", cust_dto.getCustImg());
				intent.putExtra("carModel", cust_dto.getCarModel());
				intent.putExtra("carImg", cust_dto.getCarImg());
				intent.putExtra("carColor", cust_dto.getCarColor());
				intent.putExtra("carBrand", cust_dto.getCarBrand());
				intent.putExtra("insurancePackage", cust_dto.getInsurancePackage());
				
				startActivity(intent);
			}else{
				Toast.makeText(this, "Invalid login"+taskId, Toast.LENGTH_LONG).show();
			}	
		}
	}

	@Override
	public void onTaskFailed(String taskId, Exception cause) {
		// TODO Auto-generated method stub
		if(taskId==loginTaskId){
			Toast.makeText(this, "Error"+taskId, Toast.LENGTH_LONG).show();
		}

	}
	

	protected void onPhotoTaken() {
		_taken = true;

		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inSampleSize = 4;

		Bitmap bitmap = BitmapFactory.decodeFile(_path, options);

		//Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.number);
//		ImageView imgInput = (ImageView) findViewById(R.id.imgInput);
//		imgInput.setImageBitmap(bitmap);

		try {
			ExifInterface exif = new ExifInterface(_path);
			int exifOrientation = exif.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);

			Log.v(TAG, "Orient: " + exifOrientation);

			int rotate = 0;

			switch (exifOrientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				rotate = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				rotate = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				rotate = 270;
				break;
			}

			Log.v(TAG, "Rotation: " + rotate);

			if (rotate != 0) {

				// Getting width & height of the given image.
				int w = bitmap.getWidth();
				int h = bitmap.getHeight();

				// Setting pre rotate
				Matrix mtx = new Matrix();
				mtx.preRotate(rotate);

				// Rotating Bitmap
				bitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, false);
			}

			// Convert to ARGB_8888, required by tess
			bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
			// bitmap = createContrast(bitmap, 50);

			// Black and White color
			/*
			 * for (int y = 0; y < bitmap.getHeight(); y++) { for (int x = 0; x
			 * < bitmap.getWidth(); x++) { int c = bitmap.getPixel(x, y); int R
			 * = (c << 8) >> 24; int G = (c << 16) >> 24; int B = (c << 24) >>
			 * 24;
			 * 
			 * if ((R + G + B) / 3 > 70) { bitmap.setPixel(x, y, Color.WHITE); }
			 * else { bitmap.setPixel(x, y, Color.BLACK); }
			 * 
			 * } }
			 */

		} catch (IOException e) {
			Log.e(TAG, "Couldn't correct orientation: " + e.toString());
		}

		// _image.setImageBitmap( bitmap );

//		ImageView imgOutput = (ImageView) findViewById(R.id.imgOutput);
//		imgOutput.setImageBitmap(bitmap);
		// imgOutput.setImageBitmap(doGreyscale(bitmap));

		Log.v(TAG, "Before baseApi");
		TessBaseAPI baseApi = new TessBaseAPI();
		Log.v(TAG, "Before baseApi");
		baseApi.setDebug(true);
		// baseApi.setVariable("tessedit_char_whitelist", "0123456789");
		// baseApi.setVariable(TessBaseAPI.VAR_CHAR_WHITELIST, "0123456789");
		//baseApi.setVariable("classify_bln_numeric_mode", "0");
		// baseApi.setVariable("tessedit_pageseg_mode", "6");
		baseApi.init(DATA_PATH, lang);
		baseApi.setImage(bitmap);
		//
		String recognizedText = baseApi.getUTF8Text();
		//
		baseApi.end();

		// You now have the text in recognizedText var, you can do anything with
		// it.
		// We will display a stripped out trimmed alpha-numeric version of it
		// (if lang is eng)
		// so that garbage doesn't make it to the display.

		if (lang.equalsIgnoreCase("eng")) {
			recognizedText = recognizedText.replaceAll("[^a-zA-Z0-9]+", " ");
		}
//		else if(lang.equalsIgnoreCase("tha"))
//		{
//			recognizedText = recognizedText.replaceAll("[^a-zA-Z0-9]+", " ");
//		}

		recognizedText = recognizedText.trim();

		if (recognizedText.length() != 0) {
			// _field.setText(recognizedText);

			licensePlateET.setText(licensePlateET.getText().toString().length() == 0 ? recognizedText
					: recognizedText);
			// _field.setSelection(_field.getText().toString().length());
		}

		// Cycle done.
	}


	public static Bitmap createContrast(Bitmap src, double value) {
		// image size
		int width = src.getWidth();
		int height = src.getHeight();

		// create output bitmap
		Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());

		// color information
		int A, R, G, B;
		int pixel;

		// get contrast value
		double contrast = Math.pow((100 + value) / 100, 2);

		// scan through all pixels
		for (int x = 0; x < width; ++x) {
			for (int y = 0; y < height; ++y) {
				// get pixel color
				pixel = src.getPixel(x, y);

				A = Color.alpha(pixel);

				// apply filter contrast for every channel R, G, B
				R = Color.red(pixel);
				R = (int) (((((R / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
				if (R < 0) {
					R = 0;
				} else if (R > 255) {
					R = 255;
				}

				G = Color.red(pixel);
				G = (int) (((((G / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
				if (G < 0) {
					G = 0;
				} else if (G > 255) {
					G = 255;
				}

				B = Color.red(pixel);
				B = (int) (((((B / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
				if (B < 0) {
					B = 0;
				} else if (B > 255) {
					B = 255;
				}

				// set new pixel color to output bitmap
				bmOut.setPixel(x, y, Color.argb(A, R, G, B));
			}
		}

		return bmOut;
	}

	public static Bitmap doGreyscale(Bitmap src) {
		// constant factors
		final double GS_RED = 0.299;
		final double GS_GREEN = 0.587;
		final double GS_BLUE = 0.114;

		// create output bitmap
		Bitmap bmOut = Bitmap.createBitmap(src.getWidth(), src.getHeight(),
				src.getConfig());
		// pixel information
		int A, R, G, B;
		int pixel;

		// get image size
		int width = src.getWidth();
		int height = src.getHeight();

		// scan through every single pixel
		for (int x = 0; x < width; ++x) {
			for (int y = 0; y < height; ++y) {
				// get one pixel color
				pixel = src.getPixel(x, y);
				// retrieve color of all channels
				A = Color.alpha(pixel);
				R = Color.red(pixel);
				G = Color.green(pixel);
				B = Color.blue(pixel);
				// take conversion up to one single value
				R = G = B = (int) (GS_RED * R + GS_GREEN * G + GS_BLUE * B);
				// set new pixel color to output bitmap
				bmOut.setPixel(x, y, Color.argb(A, R, G, B));
			}
		}

		// return final image
		return bmOut;
	}

}
